By
yusijia
Updated:
http://www.cnblogs.com/rollenholt/archive/2011/06/03/2070577.html
Student.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package lianxi;
public class Student { private String sid; private String name; public Student() { sid = "-1"; name = "nobody"; } public Student(String sid, String name) { setSid(sid); setName(name); } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return this.sid + ": " + this.name; } }
|
Students.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package lianxi;
import java.util.Iterator;
public class Students implements Iterable{ private Student[] stus; public Students(int size) { stus = new Student[size]; for (int i = 0; i < size; i++) { stus[i] = new Student(String.valueOf(i), "学生" + String.valueOf(i)); } } public Iterator iterator() { return new StudentIterator(); } private class StudentIterator implements Iterator { private int index = 0; public boolean hasNext() { return index != stus.length; } public Object next() { return stus[index++]; } public void remove() { throw new UnsupportedOperationException(); } } }
|
Lianxix.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| package lianxi;
import java.util.*; import java.io.*; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.reflect.InvocationTargetException;
public class lianxix { public static void main(String[] args) { Students students = new Students(10); for (Object obj : students) { Student stu = (Student) obj; System.out.println(stu.getSid() + ":" + stu.getName()); } } } 输出: 0:学生0 1:学生1 2:学生2 3:学生3 4:学生4 5:学生5 6:学生6 7:学生7 8:学生8 9:学生9
|